$(function(){
	//匹配结尾字符串
	String.prototype.endWith=function(s){
		if(s==null||s==""||this.length==0||s.length>this.length)
			return false;
		if(this.substring(this.length-s.length)==s)
			return true;
		else
			return false;
		return true;
	}
	//匹配开头字符串
	String.prototype.startWith=function(s){
		if(s==null||s==""||this.length==0||s.length>this.length)
			return false;
		if(this.substr(0,s.length)==s)
			return true;
		else
			return false;
		return true;
	}
	//内容格式替换'{0}'.format('1')
	String.prototype.format = function () {
		if (arguments.length == 0) return this;
		for (var s = this, i = 0; i < arguments.length; i++)
			s = s.replace(new RegExp('\\{' + i + '\\}', 'g'), arguments[i]);
		return s;
	};

	//form 表单序列化赋值
	$.fn.extend({  
		initForm:function(options){  
			if (!options) return;
			//默认参数
			var defaults = {  
					jsonValue:options,  
					isDebug:false   //是否需要调试，这个用于开发阶段，发布阶段请将设置为false，默认为false,true将会把name value打印出来  
			}  
			//设置参数  
			var setting = defaults;  
			var form = this;  
			jsonValue = setting.jsonValue;  
			//如果传入的json字符串，将转为json对象  
			if($.type(setting.jsonValue) === "string" && setting.jsonValue !=""){  
				jsonValue = $.parseJSON(jsonValue);  
			}  
			//如果传入的json对象为空，则不做任何操作  
			if(!$.isEmptyObject(jsonValue)){
				var debugInfo = "";  
				$.each(jsonValue,function(key,value){  
					//是否开启调试，开启将会把name value打印出来  
					if(setting.isDebug){  
						alert("name:"+key+"; value:"+value);  
						debugInfo += "name:"+key+"; value:"+value+" || ";  
					}  
					var formField = form.find("[name='"+key+"']");  
					if($.type(formField[0]) === "undefined"){  
						if(setting.isDebug){  
							alert("can not find name:["+key+"] in form!!!");    //没找到指定name的表单  
						}  
					} else {  
						var fieldTagName = formField[0].tagName.toLowerCase();
						if(fieldTagName == "input"){ 
							if(formField.attr("type") == "radio"){  
								$("input:radio[name='"+key+"'][value='"+value+"']").attr("checked","checked");  
							} else if(formField.hasClass('make-switch')) {
								formField.bootstrapSwitch('state', value);
							} else if(formField.hasClass('rating-input')){
								formField.rating('update', value);
							} else {  
								formField.val(value);  
							}  
						} else if(fieldTagName == "select"){  
							//bootstrap -select 赋值方式
							if(formField.hasClass('selectpicker')){
								if(value){
									value = value.split(",");
								}
								formField.selectpicker('val', value);
							}else{
								formField.val(value);  
							}
						} else if(fieldTagName == "textarea"){  
							//do something special  
							formField.val(value);
						} else {  
							formField.val(value);  
						}  

					}  
				})  
				if(setting.isDebug){  
					alert(debugInfo);  
				}  
			}  
			return form;    //返回对象，提供链式操作  
		},
		//设置表单只读
		disabled: function(){
			if(this.children().length == 0){
				this.attr('disabled',true);
			}else{
				this.find('input,select,textarea').attr('disabled',true);
			}
		},
		//设置表单不可编辑
		readonly: function(){
			if(this.children().length == 0){
				this.attr('readonly',true);
			}else{
				this.find('input,select,textarea').attr('readonly',true);
			}	
		},
		//表单清空
		clear: function(){
			this.find('input,select,textarea').each(function(){
				$(this).val("");
			})
		},
		//jqGrid 表格刷新（清除选中状态）
		reloadTable: function(data){
			$(this).jqGrid('resetSelection');
			var postData = $(this).jqGrid("getGridParam", "postData");
			$.extend(data,postData);
			if(!$.isEmptyObject(data)){
				$(this).jqGrid('setGridParam',{
					page:'1',
					datatype:'json',
					postData: data
				});
			}
			$(this).trigger("reloadGrid");
		},
		//根据jqgrid 自带搜索框 主动刷新jqgrid
		reloadSearchTable: function(){
			$(this).jqGrid('resetSelection');
			var postData = $(this).jqGrid("getGridParam", "postData");
			var id = $(this).attr('id');
			$("#gbox_" + id + " .ui-search-input").find('input').each(function(index,node){
				if(!$(node).is(':hidden')){
					postData[node.name] = node.value;
				}
			});
			if(!$.isEmptyObject(postData)){
				$(this).jqGrid('setGridParam',{
					page:'1',
					datatype:'json',
					postData: postData
				});
			}
			$(this).trigger("reloadGrid");
		},
		//验证数字框
		numberbox: function(options){
			var defaults = {
				precision : 2, //小数精度
				format : ',',
				regular: /^\d+(\.\d*)?$/
	        }
			var options = $.extend(defaults, options);
			if(options.precision <= 0){
				options.precision = 0;
			}
			this.each(function(){
				$(this).on('keypress',function(){
					var value = this.value;
					if((event.keyCode<48 || event.keyCode>57) && event.keyCode!=46 
							|| (!options.regular.test(value) && value != "")){
						event.returnValue = false;
					}
				});
				
				$(this).wrap("<span class='numberbox-container'></span>");
				$(this).after('<input type="hidden" class="numberbox-textbox" >');
				var nextInput = $(this).next();
				if(this.id){
					var id = this.id;
					$(this).attr('id',id + "$text");
					nextInput.attr('id',id + "$value");
				}
				if(this.name){
					var name = this.name;
					nextInput.attr('name',name);
					$(this).removeAttr('name');
				}
				if(this.value){
					var value = this.value;
					nextInput.attr('value',value);
					$(this).removeAttr('value');
				}
				$(this).on('focus',function(){
					if(!this.value){
						return false;
					}
					var num = this.value.split(",");
					var sum = parseFloat(num.join("")).toFixed(options.precision);
					$(this).val(sum);
				});
				$(this).on('blur',function(){
					if(!this.value){
						return false;
					}
					var num = parseFloat(this.value).toFixed(options.precision);//保留两位小数
					$(this).next().val(num);
					if(options.format){
						var sum = num.replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g,'$1'+options.format);
						$(this).val(sum);
					}
				});
			});	
		}
	});


	//form 表单序列化取值
	$.fn.serializeObject = function() {
		var o = {};
		var a = this.serializeArray();
		$.each(a, function() {
			if (o[this.name] !== undefined) {
				if (!o[this.name]) {
					o[this.name] = [o[this.name]];
				}
				o[this.name] += "," + this.value || "";
			} else {
				o[this.name] = this.value || "";
			}
		});
		$(this).find('.make-switch').each(function(index,node){
			if(node.name){
				var status = $(node).bootstrapSwitch('state');
				o[node.name] = node.value;
			}
		});
		return o;
	};
	
	//提示语
	$.confirm = function(title, success,error) {
	    BootstrapDialog.confirm({
	        title :'提示',
	        message : title?title:'是否确认删除选择行数据',
	        type : BootstrapDialog.TYPE_WARNING, 
	        closable : true, 
	        draggable : true, 
	        btnCancelLabel : '取消',
	        btnOKLabel : '确定', 
	        btnOKClass : 'btn-warning',
	        callback : function(result) {
	            // 点击确定按钮时，result为true
	            if (result) {
	            	if($.isFunction(success)){
	            		success();
	            	}
	            }else{
	            	if($.isFunction(error)){
	            		error();
	            	}
	            }
	        }
	    });
	};
});